export interface ChatSession {
  id: number
  title: string
  messages: any[]
  modelId: number
  createdAt: number
  updatedAt: number
}

const STORAGE_KEY = 'chat_sessions'

// 使用 Symbol 来创建一个私有方法键
const saveSessions = Symbol('saveSessions')

export const chatStorage = {
  getSessions(): ChatSession[] {
    const sessions = localStorage.getItem(STORAGE_KEY)
    return sessions ? JSON.parse(sessions) : []
  },

  saveSession(session: Omit<ChatSession, 'id' | 'createdAt' | 'updatedAt'>) {
    const sessions = this.getSessions()
    const newSession = {
      ...session,
      id: Date.now(),
      createdAt: Date.now(),
      updatedAt: Date.now()
    }
    sessions.push(newSession)
    this[saveSessions](sessions)
    return newSession
  },

  updateSession(session: ChatSession) {
    const sessions = this.getSessions()
    const index = sessions.findIndex(s => s.id === session.id)
    if (index !== -1) {
      sessions[index] = {
        ...session,
        updatedAt: Date.now()
      }
      this[saveSessions](sessions)
    }
  },

  deleteSession(id: number) {
    const sessions = this.getSessions()
    const newSessions = sessions.filter(s => s.id !== id)
    this[saveSessions](newSessions)
  },

  [saveSessions](sessions: ChatSession[]) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(sessions))
  }
} 